package com.jzy.gulimall.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jzy.common.to.es.BrandEsTo;
import com.jzy.common.to.es.SkuEsTo;
import com.jzy.gulimall.search.config.ElasticSearchConfig;
import com.jzy.gulimall.search.constant.EsConstant;
import com.jzy.gulimall.search.service.ElasticUpdateService;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author jzy
 * @date 2020/9/14 21:21
 */
@Service
public class ElasticUpdateServiceImpl implements ElasticUpdateService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 修改品牌表 更新es中的数据
     */
    @Override
    public void updateEsBrand(BrandEsTo brand) {
        List<Long> skuIds = brand.getSkuIds();
        for (Long skuId : skuIds) {
            SkuEsTo skuEsTo = new SkuEsTo();
            BeanUtil.copyProperties(brand, skuEsTo);
            UpdateRequest updateRequest = new UpdateRequest(EsConstant.PRODUCT_INDEX, String.valueOf(skuId));
            updateRequest.doc(JSONUtil.toJsonStr(skuEsTo), XContentType.JSON);
            try {
                restHighLevelClient.update(updateRequest, ElasticSearchConfig.COMMON_OPTIONS);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
